from django.shortcuts import HttpResponse, render, redirect
from rest_framework.views import APIView
from bddjango.django import APIResponse
from bddjango import show_json, show_ls
import re
import requests, json
from urllib import parse


# Create your views here.
class AuthQQ(APIView):
    class QQAuth:
        auth_type = 'qq'
        client_id = "101978535"
        client_secret = "cc8d934fbbf787d3c9f7474fcaab0e31"
        redirect_url = "http://www.bodexiong.vip/api/auth/qq"
        appname = ''  # 用来判断登录的应用名
        user_authorize_url = f'https://graph.qq.com/oauth2.0/authorize?response_type=code&client_id={client_id}&redirect_uri={redirect_url}&state={appname}'  # 这个是前端登录时用的url

        def __init__(self, request):
            self.request = request

        def get_access_token_url(self, code):
            access_token_url = f'https://graph.qq.com/oauth2.0/token?grant_type=authorization_code&code={code}&client_id={self.client_id}&client_secret={self.client_secret}&redirect_uri={self.redirect_url}'
            return access_token_url

        def get_user_info_url_by_token(self, token):
            self.token = token
            user_info_url_by_token = f'https://graph.qq.com/oauth2.0/me?access_token={token}'
            return user_info_url_by_token

        def get_user_info_url_by_openid(self, openid, api_name='get_user_info'):
            assert hasattr(self, 'token'), '没有access_token: 使用本方法前, 必须先调用get_user_info_url_by_token!'
            url = f'https://graph.qq.com/user/{api_name}?access_token={self.token}&oauth_consumer_key={self.client_id}&openid={openid}'
            return url

        def _get_code(self):
            """
            不同的授权, 对应的appname获取方式不同
            """
            code = self.request.GET.get('code')

            state = self.request.GET.get('state')
            self.appname = state
            return code

        def get_my_app_name(self):
            assert hasattr(self, 'appname'), 'NoneTypeError: 必须先调用_get_code获取appname!'
            ret = self.appname
            return ret

        def _get_token(self):
            code = self._get_code()
            access_token_url = self.get_access_token_url(code)
            print(access_token_url)
            resp = requests.get(access_token_url)
            # 拿到请求后获取的信息
            print('--- resp.text ---', resp.text)
            try:
                params = parse.parse_qs(parse.urlparse('.com?' + resp.text).query)  # 拼接成url后, 用解释器提取参数
                token = params.get('access_token')[0]
            except:
                res = json.loads(resp.text)
                # 获取access_token
                token = res['access_token']
            return token

        def get_user_info_dc(self):
            token = self._get_token()
            user_info_url = self.get_user_info_url_by_token(token)
            resp = requests.get(user_info_url)
            text = resp.text

            try:
                reg = re.compile(r'\((.*?)\)')
                mc = reg.search(text)
                res = mc.group(1)
                dc = json.loads(res)
                openid, client_id = dc.get('openid'), dc.get('client_id')
            except Exception as e:
                print(e)
                raise ValueError('获取用户信息失败!' + str(e))

            url = self.get_user_info_url_by_openid(openid)

            resp = requests.get(url)
            text = resp.text
            print(text)
            user_info_dc = json.loads(text)
            return user_info_dc

    def get(self, request, *args, **kwargs):

        oauth = self.QQAuth(request)

        print('--- user_authorize_url: ', oauth.user_authorize_url)
        print('--- get_access_token_url: ', oauth.get_access_token_url(123))

        user_info_dc = oauth.get_user_info_dc()

        print(user_info_dc)

        nickname, gender, year = user_info_dc.get('nickname'), user_info_dc.get('gender'), user_info_dc.get('year')
        figureurl, province, city = user_info_dc.get('figureurl'), user_info_dc.get('province'), user_info_dc.get('city')

        print(1)

        return APIResponse(user_info_dc, 200, f'获取用户信息成功! appname: {oauth.appname}')


import random
from .sendVerifyCode import AliPhoneCode
from bddjango import api_decorator


class SendPhoneCode(APIView):
    @api_decorator
    def get(self, request, *args, **kwargs):
        request_data = request.GET
        phone_numbers = request_data.get('phone_numbers')
        code = request_data.get('code')

        assert phone_numbers and code, '手机号和验证码不能为空!'
        ret = AliPhoneCode.send_code(phone_numbers, code)
        print(ret)
        return APIResponse(ret, 200, 'ok')


"""
https://graph.qq.com/oauth2.0/show?which=Login&display=pc&client_id=


https://graph.qq.com/oauth2.0/authorize?response_type=code&client_id=101978535&scope=get_user_info&redirect_uri=http://www.bodexiong.vip/api/auth/qq
https://graph.qq.com/oauth2.0/authorize?response_type=code&client_id=101978535&redirect_uri=http://www.bodexiong.vip/api/auth/qq&state=myblog
&scope=get_user_info

https://graph.qq.com/oauth2.0/authorize?which=Login&display=pc&response_type=code&client_id=101978535&redirect_uri=http://www.bodexiong.vip/api/auth/qq&state=myblog
"""
